﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace UDITest
{
    public partial class FrmMain : Form
    {
        CameraTool _cameraTool = new CameraTool();
        SerialTool _serialTool = new SerialTool();

        private byte[] StartByte = new byte[3];
        private byte[] EndByte = new byte[3];

        readonly string DataStartKey = "[{\"";
        readonly string base64StartKey = "base64,";
        readonly string DataEndKey = "\"}]";
        readonly int imgByteLen = 1078 + 1280 * 800;
        readonly string startPath = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase;


        void UIdo(Action action)
        {
            try
            {
                Invoke(new Action(() => action?.Invoke()));
            }
            catch (Exception)
            {
                action?.Invoke();
            }
        }

        public FrmMain()
        {
            StartByte = Encoding.ASCII.GetBytes(DataStartKey);
            EndByte = Encoding.ASCII.GetBytes(DataEndKey);
            //var x = File.ReadAllBytes(@"C:\Users\Administrator\Desktop\A\eab0c3df4d3e41308a9cf19e6bf4ce09.data");

            //var xx = System.Text.Encoding.ASCII.GetString(x);

            InitializeComponent();
            txtCamera.Enabled = false;
            FormClosing += (s, e) =>
            {
                Stop();
                Process.GetCurrentProcess().Kill();
            };

            //byte[] data = File.ReadAllBytes("C:\\Users\\Administrator\\Desktop\\2.data");
            //AnalyseData(data);
        }

        List<byte> recData = new List<byte>();

        static object lockobj = new object();

        public void Start()
        {
            try
            {
                //_cameraTool.Conn(txtCamera.Text, bmp =>
                //{
                //    UIdo(() => { pic.Image = bmp; });
                //});

                recData.Clear();

                int count = _serialTool.Open(txtVID.Text, txtPID.Text, data =>
                {
                    //int x = 0;
                    AnalyseData(data);

                    //lock (lockobj)
                    //{
                    //    for (int i = 0; i < data.Length; i++)
                    //    {
                    //        if (data[i] == StartByte[0])
                    //        {
                    //            recData.Clear();
                    //            recData.Add(data[i]);
                    //        }

                    //        if (recData.Count > 0)
                    //        {
                    //            recData.Add(data[i]);
                    //        }

                    //        if (data[i] == EndByte[EndByte.Length - 1])
                    //        {
                    //            AnalyseData(recData.ToArray());
                    //            recData.Clear();
                    //        }
                    //    }
                    //}
                });

                UIdo(() =>
                {
                    lblTitle.Text = $"连接 {count} 个设备";
                });
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);

                Task.Run(() =>
                {
                    Thread.Sleep(1000);
                    UIdo(() =>
                    {
                        Stop();
                        txtPID.Enabled = txtVID.Enabled = true;
                        lblTitle.Text = "断开";
                        rcb.Text = null;
                        pic.Image = null;
                        btnConn.Text = "连接";
                    });
                });

            }

        }

        private void Stop()
        {
            _serialTool.Close();
            //_cameraTool.ShutCamera();
        }


        private void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            SerialPort serialPort = (SerialPort)sender;
            string res = serialPort.ReadExisting();
            UIdo(() => rcb.Text = res);
        }

        private void btnConn_Click(object sender, EventArgs e)
        {
            if (btnConn.Text == "连接")
            {
                Start();
                txtPID.Enabled = txtVID.Enabled = false;
                btnConn.Text = "断开";
            }
            else
            {
                Stop();
                txtPID.Enabled = txtVID.Enabled = true;
                lblTitle.Text = "断开";
                rcb.Text = null;
                pic.Image = null;
                btnConn.Text = "连接";
            }
        }



        /// <summary>
        /// 解析数据
        /// </summary>
        /// <param name="data"></param>
        private void AnalyseData(byte[] data)
        {
            string dataStr = Encoding.ASCII.GetString(data);

            var start = dataStr.IndexOf(base64StartKey) + base64StartKey.Length;
            var end = dataStr.IndexOf("\"}]");
            try
            {
                var imgData = data.Skip(start).Take(end - start).ToArray();
                using (MemoryStream ms = new MemoryStream(imgData))
                {
                    UIdo(() =>
                    {
                        try
                        {
                            pic.Image = Image.FromStream(ms);
                        }
                        catch (Exception ex)
                        {
                            File.AppendAllText(Path.Combine(startPath, "udi.log"), ex.Message);
                            MessageBox.Show($"图像解析失败：{ex.Message}");
                        }
                       
                    });
                }

                var base64 = Convert.ToBase64String(imgData);
                string res = dataStr.Substring(0, start) + base64 + DataEndKey;
                var jsonObj = JsonConvert.DeserializeObject<List<UDICode>>(res);
                string json = JsonConvert.SerializeObject(jsonObj, Formatting.Indented);
                UIdo(() =>
                {
                    rcb.Text = DateTime.Now.ToString("HH:mm:ss") + ":\n" + json;
                });
            }
            catch (Exception ex)
            {
                File.AppendAllText(Path.Combine(startPath, "udi.log"), ex.Message);
                MessageBox.Show("数据格式不正确");
            }

        }
    }
}
